const Koa = require('koa')

const router = require('koa-router')()

const bodyParser = require('koa-bodyparser')

const controller = require('./controller')

const templating = require('./templating')

const model = require('./model');

const app = new Koa()

const isProduction = process.env.NODE_ENV === 'production'

let Pet = model.Pet

let now = Date.now()

Pet.create({
  id: 'g-' + now,
  name: 'Gaffey',
  gender: false,
  birth: '2007-07-07',
  createAt: now,
  updateAt: now,
  version: 0
}).then((p) => {
  console.log('created.' + JSON.stringify(p))
}).catch((err) => {
  console.log('failed: ' + err)
})

app.use(async (ctx, next) => {
  console.log(`Process ${ctx.request.method} ${ctx.request.url}...`)
  let
    start = new Date().getTime(),
    execTime
  await next()
  execTime = new Date().getTime() - start
  ctx.response.set('X-Response-Time', `${execTime}ms`)
})

if (! isProduction) {
  let staticFiles = require('./static-files')
  app.use(staticFiles('/static/', __dirname + '/static'))
}

app.use(require('koa-static')(__dirname + '/static/lib'))

app.use(bodyParser())

app.use(templating('views', {
  noCache: !isProduction,
  watch: !isProduction
}))

app.use(controller())

module.exports = app
